/*
 * Copyright 2020 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.seppiko.chart.utils;

import org.seppiko.chart.models.ControllerEntity;
import org.seppiko.chart.models.MessageEntity;
import org.seppiko.chart.utils.logging.LoggingManager;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;

/**
 * Response Util for Controller
 *
 * @author Leonard Woo
 */
public class ResponseUtil {

  private static LoggingManager Logger = LoggingManager.getInstance().getLogger(ResponseUtil.class.getName());

  public static ResponseEntity<byte[]> sendResponse(ControllerEntity entity) {
    if (entity == null) {
      entity = new ControllerEntity(500, MediaType.APPLICATION_JSON,
          JsonUtil.toJson(new MessageEntity(500, "SERVER ERROR")).getBytes());
      Logger.error("Response Content is NULL.");
    }
    return sendResponse(entity.getStatus(), entity.getMediaType(), entity.getData());
  }

  public static ResponseEntity<byte[]> sendResponse(int status, MediaType type, byte[] content) {
    return ResponseEntity.status(status).contentType(type).contentLength(content.length).body(content);
  }
}
